package com.adams.app.ui.fragment;

import java.io.File;

import org.json.JSONException;
import org.json.JSONObject;

import android.annotation.SuppressLint;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.adams.app.R;
import com.adams.app.common.Global;
import com.adams.app.utils.WebAccessTools;
import com.adams.app.utils.Week;

/**
 * 
 * @author ChengBin
 * 
 */
@SuppressLint("SdCardPath")
public class WeatherFragment extends Fragment {

	// 当前Activity的根布局
	private LinearLayout rootLayout;
	private TextView cityNameText;
	private ImageView currImage;
	private TextView currTmpText;
	private TextView currConditionText;
	private TextView currhumidityText;
	private TextView currWindConditionText;
	private View rootView;
	private Button refreshBtn;
	// 通过检查程序中的缓存文件判断程序是否是第一次运行
	private String dirPath = "/data/data/com.weather.app/shared_prefs/";
	private File file = new File(dirPath);

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		rootView = inflater
				.inflate(R.layout.fragment_weather, container, false);
		return rootView;
	}

	@Override
	public void onViewCreated(View view, Bundle savedInstanceState) {
		super.onViewCreated(view, savedInstanceState);

		initView(view);
		loadData(view);
	}

	private void initView(View view) {
		cityNameText = (TextView) view.findViewById(R.id.day02_city);
		currImage = (ImageView) view.findViewById(R.id.day02_currImage);
		currTmpText = (TextView) view.findViewById(R.id.day02_currTmp);
		currConditionText = (TextView) view
				.findViewById(R.id.day02_currCondition);
		currhumidityText = (TextView) view
				.findViewById(R.id.day02_currhumidity);
		currWindConditionText = (TextView) view
				.findViewById(R.id.day02_currWindCondition);
		refreshBtn = (Button) view.findViewById(R.id.day02_refresh);
		refreshBtn.setOnClickListener(freshListener);
	}

	public void loadData(View view) {

		// 如果文件不存在说明是第一次动行
		if (!file.exists()) {
			// 设置默认的壁纸
			Editor editor = getActivity().getSharedPreferences(
					Global.WALLPAPER_FILE, Context.MODE_PRIVATE).edit();
			editor.putInt("wellpaper", R.drawable.app_bg02);
			editor.commit();
		} else { // 如果文件存在
			// 设置壁纸为文件中保存的
			SharedPreferences sp = getActivity().getSharedPreferences(
					Global.WALLPAPER_FILE, Context.MODE_PRIVATE);
			rootLayout.setBackgroundResource(sp.getInt("wellpaper",
					R.drawable.app_bg02));
		}

		// 得到保存的城市天气
		SharedPreferences sp = getActivity().getSharedPreferences(
				Global.CITY_CODE, Context.MODE_PRIVATE);
		String cityCode = sp.getString("code", "");
		if (cityCode != null && cityCode.trim().length() != 0) {
			SharedPreferences shared = getActivity().getSharedPreferences(
					Global.STORE_WEATHER, Context.MODE_PRIVATE);
			long currentTime = System.currentTimeMillis();
			// 得到天气缓冲文件中的有效期
			long vaildTime = shared.getLong("validTime", currentTime);
			// 比较天气缓存文件中的有效期，如果超时了，则访问网络更新天气
			if (vaildTime > currentTime)
				setWeatherSituation(shared);
			else
				setWeatherSituation(cityCode);
		} else {
			SharedPreferences.Editor editor = sp.edit();
			editor.putString("code", "101272101");
			editor.commit();
			setWeatherSituation("101272101");
		}

	}

	private void setWeatherSituation(SharedPreferences shared) {
		// 得到城市
		String info = shared.getString("city", "");
		cityNameText.setText(info);

		// 得到温度
		info = shared.getString("temp1", "");
		currTmpText.setText("温度:" + info);
		
		// 得到天气
		info = shared.getString("weather1", "");
		currConditionText.setText("天气:" + info);
	
		// 天气图标
		int weather_icon = shared.getInt("img_title1", R.drawable.weathericon_condition_17);
		currImage.setBackgroundResource(weather_icon);

		// 得到风向
		info = shared.getString("wind1", "");
		currWindConditionText.setText("风向:" + info);
	
		// 旅游指数
		info = shared.getString("index_tr", "");
		currhumidityText.setText("旅游指数:" + info);
		
		for (int i = 0; i < 4; i++) {
			View weatherView = rootView.findViewWithTag("lv_" + i);
			setOtherData(weatherView, shared, i); // 设置周几天气
		}
	}

	private void setOtherData(View view, SharedPreferences shared, int i) {
		TextView day_of_week = (TextView) view.findViewById(R.id.day_of_week);
		ImageView day_of_image = (ImageView) view
				.findViewById(R.id.day_of_image);
		TextView day_of_weather = (TextView) view
				.findViewById(R.id.day_of_weather);
		TextView day_of_temp = (TextView) view.findViewById(R.id.day_of_temp);
		int j = i + 2;

		// 天气
		String info = String.valueOf(shared.getString("weather" + j, ""));
		day_of_weather.setText(info);

		// 温度
		info = String.valueOf(shared.getString("temp" + j, ""));
		day_of_temp.setText(info);

		// 图片
		int img = shared.getInt("img_title" + j, R.drawable.weathericon_condition_17);
		day_of_image.setBackgroundResource(img);

		info = shared.getString("day" + j, "");
		day_of_week.setText(info);
	}

	// 由城市码设置天气情况,并将得到的信息保存在文件中
	public void setWeatherSituation(String cityCode) {
		Log.e("error", cityCode + "");
		final String info = "http://m.weather.com.cn/data/" + cityCode
				+ ".html";
		new Thread() {
			public void run() {
				String result = new WebAccessTools().getWebContent(info);
				Message msg = new Message();
				msg.obj = result;
				msg.what = Global.WHEATHER;
				handler.sendMessage(msg);
			}
		}.start();
	}

	/**
	 * 接收并解析从子线程发送的message
	 * 
	 */
	private Handler handler = new Handler() {
		public void handleMessage(Message msg) {
			super.handleMessage(msg);
			if (msg.what == Global.WHEATHER) {
				if (msg.obj == null)
					return;
				parseJson(msg.obj);
			}
		}
	};

	private void parseJson(Object obj) {
		String info = "";
		try {
			JSONObject json = new JSONObject(String.valueOf(obj))
					.getJSONObject("weatherinfo");
			SharedPreferences.Editor editor = getActivity()
					.getSharedPreferences(Global.STORE_WEATHER,
							Context.MODE_PRIVATE).edit();
			if (editor == null) return;
			// 得到城市
			info = json.getString("city");
			cityNameText.setText(info);
			editor.putString("city", info);

			// 得到温度
			info = json.getString("temp1");
			currTmpText.setText("温度:" + info);
			editor.putString("temp1", info);

			// 得到天气
			info = json.getString("weather1");
			currConditionText.setText("天气:" + info);
			editor.putString("weather1", info);

			// 天气图标
			info = json.getString("img_title1");
			int weather_icon = getWeatherBitMapResource(info);
			currImage.setBackgroundResource(weather_icon);
			editor.putInt("img_title1", weather_icon);

			// 得到风向
			info = json.getString("wind1");
			currWindConditionText.setText("风向:" + info);
			editor.putString("wind1", info);

			// 旅游指数
			info = json.getString("index_tr");
			currhumidityText.setText("旅游指数:" + info);
			editor.putString("index_tr", info);

			for (int i = 0; i < 4; i++) {
				View weatherView = rootView.findViewWithTag("lv_" + i);
				setOtherData(editor, weatherView, json, i); // 设置周几天气
			}

			// 设置一个有效日期为5小时
			long validTime = System.currentTimeMillis();
			validTime = validTime + 5 * 60 * 60 * 1000;
			editor.putLong("validTime", validTime);

			// 保存
			editor.commit();
			Global.isRefresh = false;
		} catch (JSONException e) {
			e.printStackTrace();
		}
	}

	Week w = null;

	private void setOtherData(Editor editor, View view, JSONObject json, int i)
			throws JSONException {
		if (json == null) return;
		TextView day_of_week = (TextView) view.findViewById(R.id.day_of_week);
		ImageView day_of_image = (ImageView) view
				.findViewById(R.id.day_of_image);
		TextView day_of_weather = (TextView) view
				.findViewById(R.id.day_of_weather);
		TextView day_of_temp = (TextView) view.findViewById(R.id.day_of_temp);
		int j = i + 2;

		// 天气
		String info = String.valueOf(json.getString("weather" + j));
		editor.putString("weather" + j, info);
		day_of_weather.setText(info);

		// 温度
		info = String.valueOf(json.getString("temp" + j));
		editor.putString("temp" + j, info);
		day_of_temp.setText(info);

		// 图片
		int img = getWeatherBitMapResource(String.valueOf(json
				.getString("img_title" + j)));
		editor.putInt("img_title" + j, img);
		day_of_image.setBackgroundResource(img);

		String week = null;
		if (w == null) { // 如果w为空
			week = json.getString("week");
		} else {
			week = w.next();
		}
		w = Week.getDayOfWeek(week);
		info = w.next();
		editor.putString("day" + j, info);
		day_of_week.setText(info);
	}
	
	//更新监听
	OnClickListener freshListener = new OnClickListener() {
		public void onClick(View arg0) {
			if (!Global.isRefresh) {
				SharedPreferences sp = getActivity().getSharedPreferences(
						Global.CITY_CODE, Context.MODE_PRIVATE);
				w = null;
				sp.edit().putString("code", "").commit();
				Toast.makeText(getActivity(), "开始更新，请稍等..", 1).show();
				loadData(rootView);
				Global.isRefresh = true;
			} else {
				Toast.makeText(getActivity(), "正在刷新，请稍等..", 1).show();
			}
		}
	};

	/**
	 * 
	 * @description 根据返回的天气选择图片
	 * 
	 * @author ChengBin
	 * @date 2014年1月3日下午5:03:27
	 * @param weather
	 * @return
	 */
	public static int getWeatherBitMapResource(String weather) {
		if (weather.equals("晴")) {
			return R.drawable.day02_p11;
		} else if (weather.equals("多云") || weather.equals("晴转多云")) {
			return R.drawable.day02_p10;
		} else if (weather.equals("阴")) {
			return R.drawable.day02_p01;
		} else if (weather.equals("雾")) {
			return R.drawable.day02_p08;
		} else if (weather.equals("沙尘暴")) {
			return R.drawable.day02_p06;
		} else if (weather.equals("阵雨")) {
			return R.drawable.day02_p04;
		} else if (weather.equals("小雨") || weather.equals("小到中雨")) {
			return R.drawable.day02_p02;
		} else if (weather.equals("大雨")) {
			return R.drawable.day02_p03;
		} else if (weather.equals("雷阵雨")) {
			return R.drawable.day02_p05;
		} else if (weather.equals("小雪")) {
			return R.drawable.day02_p09;
		} else if (weather.equals("大雪")) {
			return R.drawable.day02_p07;
		} else if (weather.equals("雨夹雪")) {
			return R.drawable.day02_p09;
		} else {
			return R.drawable.weathericon_condition_17;
		}
	}
}